package org.zoomdev.zoom.lock.modules;

import org.zoomdev.zoom.aop.Interceptor;
import org.zoomdev.zoom.aop.factory.AnnotationInterceptorFactory;
import org.zoomdev.zoom.ioc.Ioc;
import org.zoomdev.zoom.ioc.MethodParameterNamesGetter;
import org.zoomdev.zoom.ioc.impl.factories.ParameterAdapterFactory;
import org.zoomdev.zoom.lock.LockExecutor;
import org.zoomdev.zoom.lock.annotations.LockKey;

import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class LockInterceptorFactory extends AnnotationInterceptorFactory<LockKey> {
    private final MethodParameterNamesGetter getter;
    private final Ioc ioc;

    private final ConcurrentHashMap<String, Boolean> pool = new ConcurrentHashMap<>();

    public LockInterceptorFactory(MethodParameterNamesGetter getter, Ioc ioc) {
        this.getter = getter;
        this.ioc = ioc;
    }

    @Override
    protected void createInterceptor(LockKey annotation, Class<?> targetClass, Method method, List<Interceptor> interceptors) {
        ParameterAdapterFactory.ParameterAdapterResponse response = ParameterAdapterFactory.parse(annotation.value(), targetClass, method, getter);

        LockExecutor executor;
        if (annotation.cas()) {
            executor = new CasLockExecutor(pool, annotation.message());
        } else {
            executor = ioc.fetch(LockExecutor.class);
        }

        interceptors.add(new LockInterceptor(response.format, response.adapters, executor));
    }


}
